package ch.bfh.mobicomp.soda2.barometer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	public static final String LOG_TAG = "Barometer";
	private Intent measureIntent;
	public static Activity MAIN_ACTIVITY;
	private SharedPreferences prefs;
	private OnSharedPreferenceChangeListener listener;
	public static final String KEY_BAROMETER_CHANGED = "Barometer has changed";
	public static final String KEY_BAROMETER_VALUE = "Barometer value";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		measureIntent = new Intent(this, BarometerService.class);
		MAIN_ACTIVITY = this;
		
		Log.d(LOG_TAG, "onCreate");
		
		prefs = this.getSharedPreferences("Barometer", Context.MODE_PRIVATE);
		listener = new Listener();
			
		prefs.registerOnSharedPreferenceChangeListener(listener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		Log.d(LOG_TAG, "onCreateOptionsMenue");
		
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		startService(measureIntent);
		
		Log.d(LOG_TAG, "onResume");
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		stopService(measureIntent);
		
		Log.d(LOG_TAG, "onPause");
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		startService(measureIntent);
		
		Log.d(LOG_TAG, "onRestart");
	}

	class Listener implements  OnSharedPreferenceChangeListener {
		  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
			  Log.d(LOG_TAG, "onSharedPreferencesChangeListener");
			  	TextView tvState = (TextView)findViewById(R.id.tv_main_activity_barostate);
		    	Boolean state = prefs.getBoolean(KEY_BAROMETER_CHANGED, false);
		    	if (state)
		    	{
		    		tvState.setText("has changed");
		    	}
		    	else
		    	{
		    		tvState.setText("has not changed");
		    	}
		    	TextView tvValue = (TextView)findViewById(R.id.tv_main_activity_barovalue);
		    	Float value = prefs.getFloat(KEY_BAROMETER_VALUE, 0);
		    	tvValue.setText(Float.toString(value));
		    	
		    	Log.d(LOG_TAG, "onSharedPreferencesChangeListener 2");
		  }
		};
}
